package com.xc.pay;

import cn.hutool.core.lang.Assert;
import com.xc.pay.ali.AliPayTemplate;
import com.xc.pay.ali.constant.AliProperties;
import com.xc.pay.common.MessageTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * Filename: AliPayAutoConfiguration.java <br>
 * Description: 支付宝支付相关模板配置类<br>
 *
 * @author: rongrong <br>
 * @version: 1.0 <br>
 */
@Slf4j
// 标识  自动装配的类
@SpringBootConfiguration
/*
 * 只在有servlet运行环境是生效
 * 内部一共有三个，1.any 表示只要是web环境就起作用 2.SERVLET需要有servlet的运行时环境。
 * 3.REACTIVE响应式的web应用。跟mvc已经不是一种思想，代码的方式实现不一样，所以不可以使用。
 */
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableConfigurationProperties(AliPayProperties.class)
public class AliPayAutoConfiguration {

  @Bean
  /*如果spring中没有该bean 则生效*/
  @ConditionalOnMissingBean(AliPayTemplate.class)
  /*当开启支付宝支付时才生效*/
  @ConditionalOnProperty(value = "pay.ali.enable", havingValue = "true")
  public AliPayTemplate aliPayTemplate(AliPayProperties aliPayProperties) {
    log.info("开启支付宝支付...");
    final String appid = aliPayProperties.getAppid();
    Assert.notBlank(appid, MessageTemplate.ERROR_TEMPLATE, "appid");
    final String appPrivateKey = aliPayProperties.getAppPrivateKey();
    Assert.notBlank(appPrivateKey, MessageTemplate.ERROR_TEMPLATE, "appPrivateKey");
    final String aliPublicKey = aliPayProperties.getAliPublicKey();
    Assert.notBlank(aliPublicKey, MessageTemplate.ERROR_TEMPLATE, "aliPubliceKey");
    String serverUrl;
    if (aliPayProperties.getSandbox()) {
      log.info(MessageTemplate.PAY_ENVIRONMENT_TEMPLATE, "沙箱环境");
      serverUrl = AliProperties.SANDBOX_URL;
    } else {
      log.info(MessageTemplate.PAY_ENVIRONMENT_TEMPLATE, "正式环境");
      serverUrl = AliProperties.SERVER_URL;
    }
    return AliPayTemplate.build(serverUrl, appid, appPrivateKey, aliPublicKey, aliPayProperties);
  }
}
